package com.example.bigfile.controller;

import com.example.bigfile.common.exception.BusinessException;
import com.example.bigfile.common.response.ResponseCode;
import com.example.bigfile.common.response.ResultMsgModel;
import com.example.bigfile.entity.MultipartFileParam;
import com.example.bigfile.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * @author Wangx
 * @Title:
 * @Package
 * @Description:
 * @date 2022/9/23 16:56
 */
@RestController
@RequestMapping("/uploadController")
public class BigFileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    @PostMapping("/fileUpload")
    protected ResultMsgModel fileUpload(MultipartFileParam param){

        ResultMsgModel model = new ResultMsgModel();
        //本地文件存储路径
        String root = "D://testUpload";
        File file = new File(root);
        String path=file.getAbsolutePath();
        try {
            param.setTaskId(param.getIdentifier());
            //获取已上传的片数
            int[] uploaded = fileUploadService.getUploaded(param,param.getTaskId(),path);
            if(uploaded.length==param.getTotalChunks()){
                return ResultMsgModel.successMsg("上传完成");
            }
            fileUploadService.chunkUploadByMappedByteBuffer(param,path);
            model.setCode(ResponseCode.RETURN_SUCCESS);
            model.setMsg("上传中");
        }
        catch (BusinessException e){
            new BusinessException("不是相同的文件");
            return ResultMsgModel.error("不是相同的文件");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsgModel.error("上传失败");
        }
        return model;
    }

}
